#! /usr/bin/python

import pyraf
from pyraf import iraf
from pyraf.iraf import noao, obsutil
from pyraf.irafpar import IrafParList

class ExposureTimeCalc():
    """
    This class is used by Chimera and uses the IRAF ccdtime task.
    """

    def __init__(self):   
        self.params = self.getParams()

    def ccdtime(self,method,**kwargs):
        """
        This function calculates exposure time, magnitude, or signal to noise ratio 
        for the given set of parameters.The initial parameters are the current saved 
        parameters from iraf unless otherwise specified in the method parameters.
        """
        while (method != 'time') and (method != 'magnitude') and (method != 'snr'):
            print 'Unrecognizable request: Method parameter does not match.'
            method = raw_input('Which method would you like to call?:(time,magnitude,snr) ')           

        index = dict(zip(self.label,range(len(self.plist))))
        line = []
        filters = []
        ok = 0

        for key in kwargs:
            self.params[key] = kwargs[key]
            self.plist[index[key]].set(kwargs[key])
            if key[0:1] == 'f':
                filters.append(kwargs[key])
                line.append(6 + int(key[1:2]))
                ok = 1
            else:
                pass
        if ok == 0:
            print 'No filter specified.'
            ask = raw_input('What are the filters you want to use?:(i.e. U,B,R) ')
            filters = ask.split(',')
            for i in range(len(filters)):
                self.plist[10+i].set(filters[i])
                line.append(7 + i) 
        else:
            pass
            
        if self.params['telescope'] == '?':
            choices = iraf.ccdtime(Stdout=1)
            for i in range(len(choices)):
                if choices[i][12:15] != 'det':
                    print choices[i]
                else:
                    break
            telescope = raw_input('Which telescope do you want to use?(your choices are listed above): ')
            self.params['telescope'] = telescope
            self.plist[4].set(telescope)
        else:
            pass

        if self.params['detector'] == '?':
            choices = iraf.ccdtime(Stdout=1)
            check = 0
            for i in range(len(choices)):
                if (choices[i][12:15] == 'det') or (check != 0):
                    print choices[i]
                    check = check + 1
                else:
                    pass
            detector = raw_input('Which ccd do you want to use?(your choices are listed above): ')
            self.params['detector'] = detector
            self.plist[5].set(detector)
        else:
            pass
        iraf.ccdtime.saveParList()
        if method == 'time':
            self.plist[0].set('INDEF')
            out = iraf.ccdtime(Stdout=1)
            self.result = []
            for i in range(len(filters)):
                self.result.append(float(out[line[i]][7:15]))
        elif method == 'magnitude':
            self.plist[1].set('INDEF')
            out = iraf.ccdtime(Stdout=1)
            self.result = []
            for i in range(len(filters)):
                self.result.append(float(out[line[i]][18:24]))
        elif method == 'snr':
            self.plist[2].set('INDEF')
            out = iraf.ccdtime(Stdout=1)
            self.result = []
            for i in range(len(filters)):
                self.result.append(float(out[line[i]][26:31]))
        else:
            pass
        
        return self.result

    def getParams(self):
        """
        This function asks IRAF's ccdtime task what the current saved parameters are
        and then saves these values along with their field keyword in a dictionary.
        """
        self.plist = iraf.ccdtime.getParList()
        self.label = []
        self.values = []
        for i in range(len(self.plist)):
            param = self.plist[i].get()
            self.values.append(param)
            k = str(self.plist[i])
            check = 0
            for j in range(len(k)):
                m = k[j]
                if m == ' ':
                    if check == 1:
                        self.label.append(k[first:j])
                        check += 1 
                    else:
                        first = j + 1
                        check += 1
                else:
                    pass
        params = dict(zip(self.label,self.values))
        return params
                

if __name__ == "__main__": 
     etc = ExposureTimeCalc() 
     etc.ccdtime(method='magnitude',database='ccdtime$kpno.dat',telescope='?',detector='?',snr=18,time=56,filter1='U')
     print etc.result
     print 'done'
